// pages/start/start.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    angle: 0,
    status: false, //是否通过审核
    remind: '加载中',
    checkUser: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onGetOpenid();
    this.onQueryProfile();
    setTimeout(()=>{
      this.setData({
        remind: false
      })
    },1000)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
  },

  goTo:function(){
    var that = this;
    let arr = this.data.arr;
    let openid = this.data.openid;
    if(arr.indexOf(openid) == -1){
      let url = '../wechat/wechat';
      wx.navigateTo({
        url: url
      })
    }else{
      that.doNext();
    }
    wx.hideLoading();
  },
  doNext(){
    wx.switchTab({
      url: "../home/home"
    })
  },
  onGetOpenid: function() {
    // 调用云函数
    let that = this;
    wx.cloud.callFunction({
      name: 'login',
      data: {

      }
    })
    .then(res => {
      console.log('[云函数] [login]: ', res)
      let openid = res.result.openid;
      app.globalData.openid = openid;
      that.setData({
        openid:openid
      },async ()=>{
        const db = wx.cloud.database();
        const res = await db.collection('profiles').where({
          _openid: openid
        }).count();
        console.log(res);
        if(res.total > 0){
          that.queryProfile(openid);
        }
      });
      
    }).catch(err => {
      console.error('[云函数] [login] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
  },
  queryProfile: function(openid){
    let that = this;
    const db = wx.cloud.database()
    db.collection('profiles')
    .doc(openid)
    .get()
    .then((res)=>{
      console.log('[数据库] [查询记录] 成功: ', res);
      app.globalData.category = res.data.category;
      app.globalData.userInfo = res.data.userInfo
    })
    .catch((err)=>{
      console.log(err)
      console.error('[数据库] [查询记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
    })
  },
  onQueryProfile: function(){
    let that = this;
    const db = wx.cloud.database()
    db.collection('profiles')
    .get()
    .then((res)=>{
      console.log('[数据库] [查询记录] 成功: ', res);
      let items = res.data;
      let arr = [];
      items.forEach(element => {
        arr.push(element._openid);
      });
      this.setData({
        arr
      },()=>{
        console.log('当前授权用户列表');
        console.log(this.data.arr);
      })
    })
    .catch((err)=>{
      console.log(err)
      console.error('[数据库] [查询记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
    })
  }

})